from threading import Thread, Lock
from time import sleep


class Account:
    def __init__(self, name, money):
        self.name = name
        self.money = money


def get_money(operator, drawing_money):
    lock1.acquire()  # 加锁范围必须是判断和取款为一个整体，否则依然会同时执行操作。如果仅仅对取款加锁，依然会出现在加锁之前都判定为余额足够
    if drawing_money > a1.money:
        print(f'{operator}操作时，余额不足，无法提取')
        return
    # sleep一定要在判断完成后、执行取款动作之前才能造成误判，否则没有阻塞过程
    sleep(1)  # #判断完后阻塞。其他线程开始运行
    a1.money -= drawing_money
    lock1.release()
    # sleep(1)
    print(f'{operator}取走了{drawing_money}元')


if __name__ == '__main__':
    lock1 = Lock()
    a1 = Account('金球的账户', 100)
    t1 = Thread(target=get_money, args=('张三', 60,))
    t2 = Thread(target=get_money, args=('李四', 60,))
    t1.start()
    t2.start()
